package io.github.libkodi.vertxauth;

import java.util.ArrayList;

import io.github.libkodi.basic_gateway.component.AbstractCompoent;
import io.github.libkodi.vertxauth.data.AuthDataCenter;
import io.github.libkodi.vertxauth.deal.Dealm;
import io.github.libkodi.vertxauth.filter.Filter;
import io.vertx.core.Future;
import io.vertx.ext.web.RoutingContext;

public class VertxWebAuth extends AbstractCompoent {
	private ArrayList<Filter> filters = new ArrayList<Filter>();
	private Object mutex;
	private AuthDataCenter authDataCenter = null;
	
	@Override
	public void init() {
		mutex = this;
		authDataCenter = ctx.components().get(AuthDataCenter.class).result();
		
		if (authDataCenter == null) {
			authDataCenter = new AuthDataCenter(ctx);
		} else {
			authDataCenter._setContext(ctx);
		}
	}
	
	public void filter(String match, Dealm filter) {
		synchronized (mutex) {
			filters.add(new Filter(match, filter));
		}
	}
	
	public Future<Void> verify(RoutingContext context) {
		return Future.future(promise -> {
			for (Filter filter : filters) {
				if (filter.isMatch(context.request().path())) {
					filter.dealm(this, context).onSuccess(promise::complete)
					.onFailure(promise::fail);
					break;
				}
			}
			
			promise.complete();
		});
	}

	public AuthDataCenter data() {
		return authDataCenter;
	}
}
